﻿
using PacoToolKit.Format;
namespace Protocol.SouthGridProtocol.Blocks
{
    public class C
    {
        /// <summary>
        /// 传输方向位,DIR=0：表示此帧报文是由主站发出的下行报文； DIR=1：表示此帧报文是由终端发出的上行
        /// </summary>
        public int dir;

        /// <summary>
        /// 启动标志位,PRM =1：表示此帧报文来自启动站；PRM =0：表示此帧报文来自从动站
        /// </summary>
        public int prm;

        /// <summary>
        /// 帧计数位FCB(下行方向)
        /// </summary>
        public int? fcb;

        /// <summary>
        /// 请求访问位ACD(上行方向)
        /// </summary>
        public int? acd;

        /// <summary>
        /// 帧计数有效位FCV ,FCV=1：表示FCB位有效；FCV=0：表示FCB位无效
        /// </summary>
        public int fcv;

        /// <summary>
        /// 见5.1.3.6  功能码
        /// </summary>
        public int funcCode;

        public C(string hexC)
        {
            string bin = Formater.DECtoBIN(Formater.HEXtoDEC(hexC), 8);
            dir = int.Parse(bin.Substring(0, 1));
            prm = int.Parse(bin.Substring(1, 1));
            if (dir.Equals(0))
            {
                //下行
                fcb = int.Parse(bin.Substring(2, 1)); acd = null;
            }
            else
            {
                //上行
                acd = int.Parse(bin.Substring(2, 1)); fcb = null;
            }
            fcv = int.Parse(bin.Substring(3, 1));
            funcCode = int.Parse(Formater.BINtoDEC(bin.Substring(4, 4)));
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="dir">DIR=0：表示此帧报文是由主站发出的下行报文； DIR=1：表示此帧报文是由终端发出的上行</param>
        /// <param name="prm">PRM =1：表示此帧报文来自启动站；PRM =0：表示此帧报文来自从动站</param>
        /// <param name="fcb">帧计数位FCB(下行方向)</param>
        /// <param name="acd">请求访问位ACD(上行方向)</param>
        /// <param name="fcv">FCV=1：表示FCB位有效；FCV=0：表示FCB位无效</param>
        /// <param name="funcCode">见5.1.3.6  功能码</param>
        public C(int dir, int prm, int? fcb, int? acd, int fcv, int funcCode)
        {
            this.dir = dir; this.prm = prm; this.fcb = fcb; this.acd = acd; this.fcv = fcv; this.funcCode = funcCode;
        }
        /// <summary>
        /// 组合成C hex string 
        /// </summary>
        /// <returns></returns>
        public string encodeC()
        {
            if (dir.Equals(0))
            {
                return Formater.DECtoHEX(Formater.BINtoDEC(dir.ToString() + prm.ToString() + fcb.ToString() + fcv.ToString() + Formater.DECtoBIN(funcCode.ToString(), 4)), 2).ToUpper();
            }
            else
            {
                return Formater.DECtoHEX(Formater.BINtoDEC(dir.ToString() + prm.ToString() + acd.ToString() + fcv.ToString() + Formater.DECtoBIN(funcCode.ToString(), 4)), 2).ToUpper();
            }
        }
    }
}
